// 留言与订阅管理系统
class MessagesManager {
    constructor() {
        this.currentSection = 'messages';
        this.currentPage = 1;
        this.pageSize = 10;
        this.selectedItems = new Set();
        this.batchMode = false;
        this.baseUrl = 'http://localhost:3001';
        
        this.messagesData = [];
        this.subscriptionsData = [];
        
        this.init();
    }

    // 初始化系统
    init() {
        this.setupEventListeners();
        this.loadMessages();
        this.setupSearch();
        this.renderStatsCards();
        this.renderCharts();
        console.log('留言与订阅管理系统已初始化');
    }

    // 设置事件监听器
    setupEventListeners() {
        // 搜索框实时搜索
        document.getElementById('searchInput').addEventListener('input', (e) => {
            this.handleSearch(e.target.value);
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'f') {
                e.preventDefault();
                document.getElementById('searchInput').focus();
            }
        });
    }

    // 设置搜索功能
    setupSearch() {
        let searchTimeout;
        
        document.getElementById('searchInput').addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                this.performSearch(e.target.value);
            }, 300);
        });
    }

    // 执行搜索
    performSearch(query) {
        if (this.currentSection === 'messages') {
            this.filterMessagesData(query);
        } else {
            this.filterSubscriptionsData(query);
        }
    }

    // 切换显示区域
    showSection(section) {
        // 更新菜单状态
        document.querySelectorAll('.menu-item').forEach(item => {
            item.classList.remove('active');
        });
        event.target.classList.add('active');

        // 切换内容显示
        document.getElementById('messagesSection').style.display = 
            section === 'messages' ? 'block' : 'none';
        document.getElementById('subscriptionsSection').style.display = 
            section === 'subscriptions' ? 'block' : 'none';

        this.currentSection = section;
        this.currentPage = 1;
        this.selectedItems.clear();
        this.updateSelectedCount();

        // 加载对应数据
        if (section === 'messages') {
            this.loadMessages();
        } else {
            this.loadSubscriptions();
        }
        
        // 更新数据可视化
        this.renderStatsCards();
        this.renderCharts();
    }

    // 加载留言数据
    async loadMessages() {
        try {
            const response = await fetch(`${this.baseUrl}/api/messages?page=${this.currentPage}&limit=${this.pageSize}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                this.messagesData = result.data.messages || [];
                this.renderMessagesTable(this.messagesData);
                this.renderPagination(result.data.total, 'messagesPagination');
            } else {
                this.showNotification('加载留言失败: ' + result.message, 'error');
                this.renderMessagesTable([]);
            }
        } catch (error) {
            console.error('加载留言失败:', error);
            this.showNotification('网络错误，请检查后端服务是否启动', 'error');
            this.renderMessagesTable([]);
        }
    }

    // 加载订阅数据
    async loadSubscriptions() {
        try {
            const response = await fetch(`${this.baseUrl}/api/subscriptions?page=${this.currentPage}&limit=${this.pageSize}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const result = await response.json();
            if (result.success) {
                this.subscriptionsData = result.data.subscriptions || [];
                this.renderSubscriptionsTable(this.subscriptionsData);
                this.renderPagination(result.data.total, 'subscriptionsPagination');
            } else {
                this.showNotification('加载订阅失败: ' + result.message, 'error');
                this.renderSubscriptionsTable([]);
            }
        } catch (error) {
            console.error('加载订阅失败:', error);
            this.showNotification('网络错误，请检查后端服务是否启动', 'error');
            this.renderSubscriptionsTable([]);
        }
    }

    // 渲染留言表格
    renderMessagesTable(data) {
        const tbody = document.getElementById('messagesTable');
        tbody.innerHTML = '';

        data.forEach((message, index) => {
            const row = document.createElement('tr');
            if (this.selectedItems.has(message.id)) {
                row.classList.add('row-selected');
            }

            // 处理客户信息数据映射
            const customerName = message.customer_name || message.name || '未提供姓名';
            const customerEmail = message.customer_email || message.email || '未提供邮箱';
            const customerPhone = message.customer_phone || message.phone || '未提供电话';
            const customerMobile = message.customer_mobile || message.mobile || '';
            const customerAddress = message.customer_address || message.address || '';
            const customerCity = message.customer_city || message.city || '';
            const customerCountry = message.customer_country || message.country || '';
            
            // 确定留言类型和主题
            const messageType = message.subscription_type === 'blog' ? '博客订阅' : 
                               message.subject ? message.subject : '普通留言';

            row.innerHTML = `
                <td><input type="checkbox" class="checkbox" onchange="messagesManager.toggleSelect(${message.id}, this)" ${this.selectedItems.has(message.id) ? 'checked' : ''}></td>
                <td>
                    <div><strong>${this.escapeHtml(customerName)}</strong></div>
                    <div style="font-size: 12px; color: #666;">${customerAddress} ${customerCity} ${customerCountry}</div>
                </td>
                <td>
                    <div>${this.escapeHtml(customerEmail)}</div>
                    <div style="font-size: 12px; color: #666;">${messageType}</div>
                </td>
                <td>
                    <div>${this.escapeHtml(customerPhone)}</div>
                    <div style="font-size: 12px; color: #666;">${customerMobile}</div>
                </td>
                <td>
                    <span class="status-badge ${messageType === '博客订阅' ? 'status-subscribed' : 'status-pending'}">
                        ${messageType}
                    </span>
                </td>
                <td>
                    <div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;" title="${this.escapeHtml(message.content)}">
                        ${this.escapeHtml(message.content)}
                    </div>
                </td>
                <td>${this.formatTime(message.created_at || message.time)}</td>
                <td><span class="status-badge ${message.status === 'pending' ? 'status-pending' : 'status-replied'}">${message.status === 'pending' ? '待回复' : '已回复'}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-primary" onclick="messagesManager.quickReply(${message.id})" ${message.status === 'replied' ? 'disabled' : ''}>
                            <i class="fas fa-reply"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="messagesManager.deleteMessage(${message.id})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            `;

            tbody.appendChild(row);
        });

        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" style="text-align: center; color: #666;">暂无数据</td></tr>';
        }
    }

    // 渲染订阅表格
    renderSubscriptionsTable(data) {
        const tbody = document.getElementById('subscriptionsTable');
        tbody.innerHTML = '';

        data.forEach((subscription, index) => {
            const row = document.createElement('tr');
            if (this.selectedItems.has(subscription.id)) {
                row.classList.add('row-selected');
            }

            // 处理客户信息数据映射
            const customerName = subscription.customer_name || subscription.name || '未提供姓名';
            const customerEmail = subscription.customer_email || subscription.email || '未提供邮箱';
            const customerPhone = subscription.customer_phone || subscription.phone || '未提供电话';
            const customerMobile = subscription.customer_mobile || subscription.mobile || '未提供手机';
            const customerAddress = subscription.customer_address || subscription.address || '未提供地址';
            const customerCity = subscription.customer_city || subscription.city || '';
            const customerCountry = subscription.customer_country || subscription.country || '';
            
            row.innerHTML = `
                <td><input type="checkbox" class="checkbox" onchange="messagesManager.toggleSelect(${subscription.id}, this)" ${this.selectedItems.has(subscription.id) ? 'checked' : ''}></td>
                <td>
                    <div><strong>${this.escapeHtml(customerName)}</strong></div>
                    <div style="font-size: 12px; color: #666;">${subscription.company || '个人用户'}</div>
                </td>
                <td>
                    <div>${this.escapeHtml(customerEmail)}</div>
                    <div style="font-size: 12px; color: #666;">${subscription.subscription_type === 'blog' ? '博客订阅' : subscription.subscription_type || '博客订阅'}</div>
                </td>
                <td>
                    <div>${this.escapeHtml(customerPhone)}</div>
                    <div style="font-size: 12px; color: #666;">${customerMobile}</div>
                </td>
                <td>
                    <div>${this.escapeHtml(customerAddress)}</div>
                    <div style="font-size: 12px; color: #666;">${customerCity} ${customerCountry}</div>
                </td>
                <td>${this.formatTime(subscription.created_at || subscription.time)}</td>
                <td><span class="status-badge ${subscription.status === 'subscribed' || subscription.status === 'active' ? 'status-subscribed' : 'status-unsubscribed'}">${subscription.status === 'subscribed' || subscription.status === 'active' ? '已订阅' : '已取消'}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-sm btn-secondary" onclick="messagesManager.unsubscribe(${subscription.id})" ${subscription.status === 'unsubscribed' || subscription.status === 'inactive' ? 'disabled' : ''}>
                            <i class="fas fa-ban"></i>
                        </button>
                        <button class="btn btn-sm btn-primary" onclick="messagesManager.exportSubscription(${subscription.id})">
                            <i class="fas fa-download"></i>
                        </button>
                        <button class="btn btn-sm btn-info" onclick="messagesManager.viewDetails(${subscription.id})">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </td>
            `;

            tbody.appendChild(row);
        });

        if (data.length === 0) {
            tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; color: #666;">暂无数据</td></tr>';
        }
    }

    // 渲染分页
    renderPagination(totalItems, paginationId) {
        const totalPages = Math.ceil(totalItems / this.pageSize);
        const pagination = document.getElementById(paginationId);
        
        if (totalPages <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let paginationHtml = '';
        
        // 上一页
        if (this.currentPage > 1) {
            paginationHtml += `<button class="page-btn" onclick="messagesManager.goToPage(${this.currentPage - 1})"><i class="fas fa-chevron-left"></i></button>`;
        }

        // 页码
        for (let i = 1; i <= totalPages; i++) {
            if (i === this.currentPage) {
                paginationHtml += `<button class="page-btn active">${i}</button>`;
            } else if (i >= this.currentPage - 2 && i <= this.currentPage + 2) {
                paginationHtml += `<button class="page-btn" onclick="messagesManager.goToPage(${i})">${i}</button>`;
            }
        }

        // 下一页
        if (this.currentPage < totalPages) {
            paginationHtml += `<button class="page-btn" onclick="messagesManager.goToPage(${this.currentPage + 1})"><i class="fas fa-chevron-right"></i></button>`;
        }

        pagination.innerHTML = paginationHtml;
    }

    // 切换页面
    goToPage(page) {
        this.currentPage = page;
        if (this.currentSection === 'messages') {
            this.loadMessages();
        } else {
            this.loadSubscriptions();
        }
        this.selectedItems.clear();
        this.updateSelectedCount();
    }

    // 切换选择状态
    toggleSelect(id, checkbox) {
        if (checkbox.checked) {
            this.selectedItems.add(id);
            checkbox.closest('tr').classList.add('row-selected');
        } else {
            this.selectedItems.delete(id);
            checkbox.closest('tr').classList.remove('row-selected');
        }
        this.updateSelectedCount();
    }

    // 全选/取消全选
    toggleSelectAll(checkbox) {
        const table = checkbox.closest('table');
        const checkboxes = table.querySelectorAll('input[type="checkbox"]:not(:disabled)');
        
        checkboxes.forEach((cb, index) => {
            if (index > 0) { // 跳过表头的复选框
                cb.checked = checkbox.checked;
                const id = parseInt(cb.getAttribute('onchange').match(/\d+/)[0]);
                if (checkbox.checked) {
                    this.selectedItems.add(id);
                    cb.closest('tr').classList.add('row-selected');
                } else {
                    this.selectedItems.delete(id);
                    cb.closest('tr').classList.remove('row-selected');
                }
            }
        });
        
        this.updateSelectedCount();
    }

    // 更新选中数量
    updateSelectedCount() {
        document.getElementById('selectedCount').textContent = this.selectedItems.size;
    }

    // 快速回复
    quickReply(messageId) {
        const message = this.messagesData.find(m => m.id === messageId);
        if (!message) return;

        // 移除其他快速回复框
        document.querySelectorAll('.quick-reply').forEach(reply => {
            reply.style.display = 'none';
        });

        const row = document.querySelector(`input[onchange*="${messageId}"]`).closest('tr');
        
        // 创建或显示回复框
        let replyBox = row.nextElementSibling;
        if (!replyBox || !replyBox.classList.contains('quick-reply')) {
            replyBox = document.createElement('tr');
            replyBox.className = 'quick-reply';
            replyBox.innerHTML = `
                <td colspan="6">
                    <textarea class="reply-input" placeholder="请输入回复内容..." id="replyInput_${messageId}"></textarea>
                    <div class="reply-actions">
                        <button class="btn btn-sm btn-secondary" onclick="this.closest('.quick-reply').style.display='none'">取消</button>
                        <button class="btn btn-sm btn-primary" onclick="messagesManager.sendReply(${messageId})">发送回复</button>
                    </div>
                </td>
            `;
            row.parentNode.insertBefore(replyBox, row.nextSibling);
        }
        
        replyBox.style.display = 'table-row';
    }

    // 发送回复
    sendReply(messageId) {
        const replyInput = document.getElementById(`replyInput_${messageId}`);
        const content = replyInput.value.trim();
        
        if (!content) {
            this.showNotification('请输入回复内容', 'error');
            return;
        }

        // 模拟发送回复
        const messageIndex = this.messagesData.findIndex(m => m.id === messageId);
        if (messageIndex !== -1) {
            this.messagesData[messageIndex].status = 'replied';
            this.messagesData[messageIndex].replyContent = content;
            this.messagesData[messageIndex].replyTime = new Date();
            
            this.loadMessages();
            this.showNotification('回复发送成功', 'success');
            
            // 隐藏回复框
            document.querySelector(`#replyInput_${messageId}`).closest('.quick-reply').style.display = 'none';
        }
    }

    // 删除留言
    deleteMessage(messageId) {
        if (confirm('确定要删除这条留言吗？此操作不可恢复。')) {
            this.messagesData = this.messagesData.filter(m => m.id !== messageId);
            this.selectedItems.delete(messageId);
            this.loadMessages();
            this.showNotification('留言删除成功', 'success');
        }
    }

    // 取消订阅
    unsubscribe(subscriptionId) {
        if (confirm('确定要取消此订阅吗？')) {
            const subscriptionIndex = this.subscriptionsData.findIndex(s => s.id === subscriptionId);
            if (subscriptionIndex !== -1) {
                this.subscriptionsData[subscriptionIndex].status = 'unsubscribed';
                this.subscriptionsData[subscriptionIndex].unsubscribeTime = new Date();
                this.loadSubscriptions();
                this.showNotification('订阅已取消', 'success');
            }
        }
    }

    // 导出订阅
    exportSubscription(subscriptionId) {
        const subscription = this.subscriptionsData.find(s => s.id === subscriptionId);
        if (subscription) {
            // 模拟导出操作
            const data = JSON.stringify(subscription, null, 2);
            this.downloadFile(`subscription_${subscriptionId}.json`, data);
            this.showNotification('订阅数据导出成功', 'success');
        }
    }

    // 批量删除
    batchDelete() {
        if (this.selectedItems.size === 0) {
            this.showNotification('请先选择要删除的项目', 'warning');
            return;
        }

        if (confirm(`确定要删除选中的 ${this.selectedItems.size} 个项目吗？此操作不可恢复。`)) {
            if (this.currentSection === 'messages') {
                this.messagesData = this.messagesData.filter(m => !this.selectedItems.has(m.id));
            } else {
                this.subscriptionsData = this.subscriptionsData.filter(s => !this.selectedItems.has(s.id));
            }
            
            this.selectedItems.clear();
            this.toggleBatchActions();
            
            if (this.currentSection === 'messages') {
                this.loadMessages();
            } else {
                this.loadSubscriptions();
            }
            
            this.showNotification(`成功删除 ${this.selectedItems.size} 个项目`, 'success');
        }
    }

    // 切换批量操作模式
    toggleBatchActions() {
        this.batchMode = !this.batchMode;
        const batchPanel = document.getElementById('batchActions');
        
        if (this.batchMode) {
            batchPanel.style.display = 'block';
        } else {
            batchPanel.style.display = 'none';
            this.selectedItems.clear();
            this.updateSelectedCount();
            
            // 取消所有选中状态
            document.querySelectorAll('.row-selected').forEach(row => {
                row.classList.remove('row-selected');
            });
            document.querySelectorAll('input[type="checkbox"]').forEach(cb => {
                cb.checked = false;
            });
        }
    }

    // 导出数据
    exportData() {
        let data, filename;
        
        if (this.currentSection === 'messages') {
            data = JSON.stringify(this.messagesData, null, 2);
            filename = 'messages_export.json';
        } else {
            data = JSON.stringify(this.subscriptionsData, null, 2);
            filename = 'subscriptions_export.json';
        }
        
        this.downloadFile(filename, data);
        this.showNotification('数据导出成功', 'success');
    }

    // 下载文件
    downloadFile(filename, content) {
        const blob = new Blob([content], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 显示通知
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 12px 20px;
            border-radius: 4px;
            color: white;
            z-index: 1000;
            font-size: 14px;
            transition: all 0.3s;
        `;
        
        switch (type) {
            case 'success':
                notification.style.background = '#28a745';
                break;
            case 'error':
                notification.style.background = '#dc3545';
                break;
            case 'warning':
                notification.style.background = '#ffc107';
                notification.style.color = '#000';
                break;
            default:
                notification.style.background = '#17a2b8';
        }
        
        notification.textContent = message;
        document.body.appendChild(notification);
        
        // 3秒后自动移除
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }

    // 过滤留言数据
    filterMessagesData(query) {
        // 在实际应用中，这里应该是服务器端搜索
        // 这里简单模拟前端过滤
        const filtered = this.messagesData.filter(message => 
            message.nickname.toLowerCase().includes(query.toLowerCase()) ||
            message.content.toLowerCase().includes(query.toLowerCase())
        );
        
        this.renderMessagesTable(filtered.slice(0, this.pageSize));
        this.renderPagination(filtered.length, 'messagesPagination');
    }

    // 过滤订阅数据
    filterSubscriptionsData(query) {
        const filtered = this.subscriptionsData.filter(subscription => 
            subscription.name.toLowerCase().includes(query.toLowerCase()) ||
            subscription.email.toLowerCase().includes(query.toLowerCase()) ||
            (subscription.company && subscription.company.toLowerCase().includes(query.toLowerCase()))
        );
        
        this.renderSubscriptionsTable(filtered.slice(0, this.pageSize));
        this.renderPagination(filtered.length, 'subscriptionsPagination');
    }

    // 过滤留言状态
    filterMessages(status) {
        let filtered;
        if (status === 'all') {
            filtered = this.messagesData;
        } else {
            filtered = this.messagesData.filter(message => message.status === status);
        }
        
        this.renderMessagesTable(filtered.slice(0, this.pageSize));
        this.renderPagination(filtered.length, 'messagesPagination');
    }

    // 过滤订阅状态
    filterSubscriptions(status) {
        let filtered;
        if (status === 'all') {
            filtered = this.subscriptionsData;
        } else {
            filtered = this.subscriptionsData.filter(subscription => subscription.status === status);
        }
        
        this.renderSubscriptionsTable(filtered.slice(0, this.pageSize));
        this.renderPagination(filtered.length, 'subscriptionsPagination');
    }

    // 生成模拟留言数据
    generateMessagesData() {
        const nicknames = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];
        const messages = [
            '这个产品看起来不错，什么时候有货？',
            '请问支持国际运输吗？',
            '质量怎么样？有没有保修？',
            '批量采购有优惠吗？',
            '可以定制颜色吗？',
            '发货需要多长时间？',
            '支持哪些支付方式？',
            '退货政策是怎样的？'
        ];
        
        const data = [];
        for (let i = 1; i <= 50; i++) {
            data.push({
                id: i,
                nickname: nicknames[Math.floor(Math.random() * nicknames.length)],
                content: messages[Math.floor(Math.random() * messages.length)],
                time: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000),
                status: Math.random() > 0.5 ? 'pending' : 'replied'
            });
        }
        return data;
    }

    // 生成模拟订阅数据
    generateSubscriptionsData() {
        const names = ['张伟', '王芳', '李娜', '刘洋', '陈静', '杨帆', '黄磊', '周涛'];
        const companies = ['ABC公司', 'XYZ集团', '个人用户', 'DEF企业', 'GHI有限公司'];
        
        const data = [];
        for (let i = 1; i <= 30; i++) {
            data.push({
                id: i + 1000,
                name: names[Math.floor(Math.random() * names.length)],
                email: `user${i}@example.com`,
                phone: Math.random() > 0.3 ? `138${String(i).padStart(8, '0')}` : null,
                company: companies[Math.floor(Math.random() * companies.length)],
                time: new Date(Date.now() - Math.random() * 90 * 24 * 60 * 60 * 1000),
                status: Math.random() > 0.2 ? 'subscribed' : 'unsubscribed'
            });
        }
        return data;
    }

    // 工具函数：转义HTML
    escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 工具函数：格式化时间
    formatTime(date) {
        const now = new Date();
        const diff = now - date;
        
        if (diff < 60 * 1000) {
            return '刚刚';
        } else if (diff < 60 * 60 * 1000) {
            return Math.floor(diff / (60 * 1000)) + '分钟前';
        } else if (diff < 24 * 60 * 60 * 1000) {
            return Math.floor(diff / (60 * 60 * 1000)) + '小时前';
        } else {
            return date.toLocaleDateString('zh-CN');
        }
    }

    // 处理搜索
    handleSearch(query) {
        if (this.currentSection === 'messages') {
            this.filterMessagesData(query);
        } else {
            this.filterSubscriptionsData(query);
        }
    }

    // 渲染统计卡片
    renderStatsCards() {
        const statsContainer = document.getElementById('statsCards');
        
        if (this.currentSection === 'messages') {
            const totalMessages = this.messagesData.length;
            const pendingMessages = this.messagesData.filter(m => m.status === 'pending').length;
            const repliedMessages = this.messagesData.filter(m => m.status === 'replied').length;
            const replyRate = totalMessages > 0 ? Math.round((repliedMessages / totalMessages) * 100) : 0;
            
            statsContainer.innerHTML = `
                <div class="stat-card">
                    <div class="stat-icon" style="background: #3498db;">📝</div>
                    <div class="stat-content">
                        <div class="stat-number">${totalMessages}</div>
                        <div class="stat-label">总留言数</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #f39c12;">⏳</div>
                    <div class="stat-content">
                        <div class="stat-number">${pendingMessages}</div>
                        <div class="stat-label">待回复留言</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #27ae60;">✅</div>
                    <div class="stat-content">
                        <div class="stat-number">${repliedMessages}</div>
                        <div class="stat-label">已回复留言</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #9b59b6;">📊</div>
                    <div class="stat-content">
                        <div class="stat-number">${replyRate}%</div>
                        <div class="stat-label">回复率</div>
                    </div>
                </div>
            `;
        } else {
            const totalSubscriptions = this.subscriptionsData.length;
            const activeSubscriptions = this.subscriptionsData.filter(s => s.status === 'subscribed').length;
            const inactiveSubscriptions = this.subscriptionsData.filter(s => s.status === 'unsubscribed').length;
            const retentionRate = totalSubscriptions > 0 ? Math.round((activeSubscriptions / totalSubscriptions) * 100) : 0;
            
            statsContainer.innerHTML = `
                <div class="stat-card">
                    <div class="stat-icon" style="background: #3498db;">📧</div>
                    <div class="stat-content">
                        <div class="stat-number">${totalSubscriptions}</div>
                        <div class="stat-label">总订阅数</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #27ae60;">👍</div>
                    <div class="stat-content">
                        <div class="stat-number">${activeSubscriptions}</div>
                        <div class="stat-label">活跃订阅</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #e74c3c;">👎</div>
                    <div class="stat-content">
                        <div class="stat-number">${inactiveSubscriptions}</div>
                        <div class="stat-label">取消订阅</div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon" style="background: #9b59b6;">📈</div>
                    <div class="stat-content">
                        <div class="stat-number">${retentionRate}%</div>
                        <div class="stat-label">留存率</div>
                    </div>
                </div>
            `;
        }
    }

    // 渲染图表
    renderCharts() {
        const chartsContainer = document.getElementById('chartsContainer');
        
        if (this.currentSection === 'messages') {
            // 留言状态分布饼图
            const statusData = this.getMessagesStatusDistribution();
            // 留言时间趋势图
            const timeData = this.getMessagesTimeTrend();
            // 留言主题分布
            const subjectData = this.getMessagesSubjectDistribution();
            // 客户来源分析
            const sourceData = this.getMessagesSourceAnalysis();
            
            chartsContainer.innerHTML = `
                <div class="chart-card">
                    <div class="chart-title">留言状态分布</div>
                    <canvas class="chart-canvas" id="messagesStatusChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">留言时间趋势</div>
                    <canvas class="chart-canvas" id="messagesTimeChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">留言主题分布</div>
                    <canvas class="chart-canvas" id="messagesSubjectChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">客户来源分析</div>
                    <canvas class="chart-canvas" id="messagesSourceChart"></canvas>
                </div>
            `;
            
            // 延迟渲染图表，确保DOM已加载
            setTimeout(() => {
                this.renderMessagesStatusChart(statusData);
                this.renderMessagesTimeChart(timeData);
                this.renderMessagesSubjectChart(subjectData);
                this.renderMessagesSourceChart(sourceData);
            }, 100);
        } else {
            // 订阅状态分布饼图
            const statusData = this.getSubscriptionsStatusDistribution();
            // 订阅时间趋势图
            const timeData = this.getSubscriptionsTimeTrend();
            // 订阅类型分析
            const typeData = this.getSubscriptionsTypeAnalysis();
            // 订阅偏好分析
            const preferenceData = this.getSubscriptionsPreferenceAnalysis();
            
            chartsContainer.innerHTML = `
                <div class="chart-card">
                    <div class="chart-title">订阅状态分布</div>
                    <canvas class="chart-canvas" id="subscriptionsStatusChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">订阅时间趋势</div>
                    <canvas class="chart-canvas" id="subscriptionsTimeChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">订阅类型分析</div>
                    <canvas class="chart-canvas" id="subscriptionsTypeChart"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title">订阅偏好分析</div>
                    <canvas class="chart-canvas" id="subscriptionsPreferenceChart"></canvas>
                </div>
            `;
            
            // 延迟渲染图表，确保DOM已加载
            setTimeout(() => {
                this.renderSubscriptionsStatusChart(statusData);
                this.renderSubscriptionsTimeChart(timeData);
                this.renderSubscriptionsTypeChart(typeData);
                this.renderSubscriptionsPreferenceChart(preferenceData);
            }, 100);
        }
    }

    // 获取留言状态分布数据
    getMessagesStatusDistribution() {
        const pending = this.messagesData.filter(m => m.status === 'pending').length;
        const replied = this.messagesData.filter(m => m.status === 'replied').length;
        
        return {
            labels: ['待回复', '已回复'],
            data: [pending, replied],
            colors: ['#f39c12', '#27ae60']
        };
    }

    // 获取留言时间趋势数据
    getMessagesTimeTrend() {
        // 按天统计留言数量
        const dailyCounts = {};
        this.messagesData.forEach(message => {
            const date = new Date(message.time).toLocaleDateString('zh-CN');
            dailyCounts[date] = (dailyCounts[date] || 0) + 1;
        });
        
        const labels = Object.keys(dailyCounts).sort();
        const data = labels.map(date => dailyCounts[date]);
        
        return { labels, data };
    }

    // 获取订阅状态分布数据
    getSubscriptionsStatusDistribution() {
        const subscribed = this.subscriptionsData.filter(s => s.status === 'subscribed').length;
        const unsubscribed = this.subscriptionsData.filter(s => s.status === 'unsubscribed').length;
        
        return {
            labels: ['已订阅', '已取消'],
            data: [subscribed, unsubscribed],
            colors: ['#27ae60', '#e74c3c']
        };
    }

    // 获取订阅时间趋势数据
    getSubscriptionsTimeTrend() {
        // 按天统计订阅数量
        const dailyCounts = {};
        this.subscriptionsData.forEach(subscription => {
            const date = new Date(subscription.time).toLocaleDateString('zh-CN');
            dailyCounts[date] = (dailyCounts[date] || 0) + 1;
        });
        
        const labels = Object.keys(dailyCounts).sort();
        const data = labels.map(date => dailyCounts[date]);
        
        return { labels, data };
    }

    // 渲染留言状态饼图
    renderMessagesStatusChart(data) {
        const ctx = document.getElementById('messagesStatusChart').getContext('2d');
        
        // 简单的Canvas饼图实现
        const total = data.data.reduce((sum, value) => sum + value, 0);
        let startAngle = 0;
        
        // 清除画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // 绘制饼图
        data.data.forEach((value, index) => {
            const sliceAngle = (value / total) * 2 * Math.PI;
            
            ctx.beginPath();
            ctx.moveTo(125, 125);
            ctx.arc(125, 125, 100, startAngle, startAngle + sliceAngle);
            ctx.closePath();
            ctx.fillStyle = data.colors[index];
            ctx.fill();
            
            // 绘制标签
            const angle = startAngle + sliceAngle / 2;
            const x = 125 + Math.cos(angle) * 70;
            const y = 125 + Math.sin(angle) * 70;
            
            ctx.fillStyle = '#333';
            ctx.font = '12px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(`${data.labels[index]} (${value})`, x, y);
            
            startAngle += sliceAngle;
        });
        
        // 绘制中心圆
        ctx.beginPath();
        ctx.arc(125, 125, 30, 0, 2 * Math.PI);
        ctx.fillStyle = '#fff';
        ctx.fill();
        
        // 绘制总数
        ctx.fillStyle = '#333';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(`总计\n${total}`, 125, 125);
    }

    // 渲染留言时间趋势图
    renderMessagesTimeChart(data) {
        const ctx = document.getElementById('messagesTimeChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        // 清除画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        const padding = 40;
        const chartWidth = ctx.canvas.width - padding * 2;
        const chartHeight = ctx.canvas.height - padding * 2;
        const maxValue = Math.max(...data.data);
        
        // 绘制坐标轴
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 1;
        
        // Y轴
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // X轴
        ctx.beginPath();
        ctx.moveTo(padding, ctx.canvas.height - padding);
        ctx.lineTo(ctx.canvas.width - padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // 绘制数据点
        ctx.strokeStyle = '#3498db';
        ctx.lineWidth = 2;
        ctx.fillStyle = '#3498db';
        
        ctx.beginPath();
        data.data.forEach((value, index) => {
            const x = padding + (index / (data.data.length - 1)) * chartWidth;
            const y = ctx.canvas.height - padding - (value / maxValue) * chartHeight;
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
            
            // 绘制数据点
            ctx.beginPath();
            ctx.arc(x, y, 4, 0, 2 * Math.PI);
            ctx.fill();
        });
        ctx.stroke();
        
        // 绘制X轴标签
        ctx.fillStyle = '#666';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        
        data.labels.forEach((label, index) => {
            const x = padding + (index / (data.data.length - 1)) * chartWidth;
            const y = ctx.canvas.height - padding + 20;
            
            // 简化日期显示
            const shortLabel = label.length > 8 ? label.substring(5) : label;
            ctx.fillText(shortLabel, x, y);
        });
    }

    // 渲染订阅状态饼图
    renderSubscriptionsStatusChart(data) {
        const ctx = document.getElementById('subscriptionsStatusChart').getContext('2d');
        
        const total = data.data.reduce((sum, value) => sum + value, 0);
        let startAngle = 0;
        
        // 清除画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        // 绘制饼图
        data.data.forEach((value, index) => {
            const sliceAngle = (value / total) * 2 * Math.PI;
            
            ctx.beginPath();
            ctx.moveTo(125, 125);
            ctx.arc(125, 125, 100, startAngle, startAngle + sliceAngle);
            ctx.closePath();
            ctx.fillStyle = data.colors[index];
            ctx.fill();
            
            // 绘制标签
            const angle = startAngle + sliceAngle / 2;
            const x = 125 + Math.cos(angle) * 70;
            const y = 125 + Math.sin(angle) * 70;
            
            ctx.fillStyle = '#333';
            ctx.font = '12px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(`${data.labels[index]} (${value})`, x, y);
            
            startAngle += sliceAngle;
        });
        
        // 绘制中心圆
        ctx.beginPath();
        ctx.arc(125, 125, 30, 0, 2 * Math.PI);
        ctx.fillStyle = '#fff';
        ctx.fill();
        
        // 绘制总数
        ctx.fillStyle = '#333';
        ctx.font = '14px Arial';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(`总计\n${total}`, 125, 125);
    }

    // 渲染订阅时间趋势图
    renderSubscriptionsTimeChart(data) {
        const ctx = document.getElementById('subscriptionsTimeChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        // 清除画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        const padding = 40;
        const chartWidth = ctx.canvas.width - padding * 2;
        const chartHeight = ctx.canvas.height - padding * 2;
        const maxValue = Math.max(...data.data);
        
        // 绘制坐标轴
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 1;
        
        // Y轴
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // X轴
        ctx.beginPath();
        ctx.moveTo(padding, ctx.canvas.height - padding);
        ctx.lineTo(ctx.canvas.width - padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // 绘制数据点
        ctx.strokeStyle = '#9b59b6';
        ctx.lineWidth = 2;
        ctx.fillStyle = '#9b59b6';
        
        ctx.beginPath();
        data.data.forEach((value, index) => {
            const x = padding + (index / (data.data.length - 1)) * chartWidth;
            const y = ctx.canvas.height - padding - (value / maxValue) * chartHeight;
            
            if (index === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
            
            // 绘制数据点
            ctx.beginPath();
            ctx.arc(x, y, 4, 0, 2 * Math.PI);
            ctx.fill();
        });
        ctx.stroke();
        
        // 绘制X轴标签
        ctx.fillStyle = '#666';
        ctx.font = '10px Arial';
        ctx.textAlign = 'center';
        
        data.labels.forEach((label, index) => {
            const x = padding + (index / (data.data.length - 1)) * chartWidth;
            const y = ctx.canvas.height - padding + 20;
            
            // 简化日期显示
            const shortLabel = label.length > 8 ? label.substring(5) : label;
            ctx.fillText(shortLabel, x, y);
        });
    }

    // 获取留言主题分布数据
    getMessagesSubjectDistribution() {
        const subjectCounts = {};
        this.messagesData.forEach(message => {
            const subject = message.subject || '未分类';
            subjectCounts[subject] = (subjectCounts[subject] || 0) + 1;
        });
        
        const labels = Object.keys(subjectCounts);
        const data = labels.map(subject => subjectCounts[subject]);
        
        // 生成颜色
        const colors = ['#3498db', '#e74c3c', '#f39c12', '#27ae60', '#9b59b6', '#34495e'];
        
        return { labels, data, colors: colors.slice(0, labels.length) };
    }

    // 获取客户来源分析数据
    getMessagesSourceAnalysis() {
        const sourceCounts = {};
        this.messagesData.forEach(message => {
            const source = message.source || '未知来源';
            sourceCounts[source] = (sourceCounts[source] || 0) + 1;
        });
        
        const labels = Object.keys(sourceCounts);
        const data = labels.map(source => sourceCounts[source]);
        
        return { labels, data };
    }

    // 获取订阅类型分析数据
    getSubscriptionsTypeAnalysis() {
        const typeCounts = {};
        this.subscriptionsData.forEach(subscription => {
            const type = subscription.subscription_type || '博客订阅';
            typeCounts[type] = (typeCounts[type] || 0) + 1;
        });
        
        const labels = Object.keys(typeCounts);
        const data = labels.map(type => typeCounts[type]);
        
        // 生成颜色
        const colors = ['#3498db', '#e74c3c', '#f39c12', '#27ae60', '#9b59b6'];
        
        return { labels, data, colors: colors.slice(0, labels.length) };
    }

    // 获取订阅偏好分析数据
    getSubscriptionsPreferenceAnalysis() {
        const preferenceCounts = {
            '骑行技巧': 0,
            '产品评测': 0,
            '保养知识': 0,
            '行业资讯': 0
        };
        
        this.subscriptionsData.forEach(subscription => {
            if (subscription.blog_categories) {
                try {
                    const categories = JSON.parse(subscription.blog_categories);
                    categories.forEach(category => {
                        switch(category) {
                            case 'riding_tips': preferenceCounts['骑行技巧']++; break;
                            case 'product_reviews': preferenceCounts['产品评测']++; break;
                            case 'maintenance': preferenceCounts['保养知识']++; break;
                            case 'industry_news': preferenceCounts['行业资讯']++; break;
                        }
                    });
                } catch (e) {
                    // 解析失败，跳过
                }
            }
        });
        
        const labels = Object.keys(preferenceCounts);
        const data = labels.map(pref => preferenceCounts[pref]);
        
        return { labels, data };
    }

    // 渲染留言主题分布图
    renderMessagesSubjectChart(data) {
        const ctx = document.getElementById('messagesSubjectChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        this.renderBarChart(ctx, data, '#3498db');
    }

    // 渲染客户来源分析图
    renderMessagesSourceChart(data) {
        const ctx = document.getElementById('messagesSourceChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        this.renderBarChart(ctx, data, '#e74c3c');
    }

    // 渲染订阅类型分析图
    renderSubscriptionsTypeChart(data) {
        const ctx = document.getElementById('subscriptionsTypeChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        this.renderBarChart(ctx, data, '#f39c12');
    }

    // 渲染订阅偏好分析图
    renderSubscriptionsPreferenceChart(data) {
        const ctx = document.getElementById('subscriptionsPreferenceChart').getContext('2d');
        
        if (data.labels.length === 0) {
            ctx.fillStyle = '#999';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText('暂无数据', ctx.canvas.width / 2, ctx.canvas.height / 2);
            return;
        }
        
        this.renderBarChart(ctx, data, '#27ae60');
    }

    // 通用柱状图渲染方法
    renderBarChart(ctx, data, color) {
        // 清除画布
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        
        const padding = 40;
        const chartWidth = ctx.canvas.width - padding * 2;
        const chartHeight = ctx.canvas.height - padding * 2;
        const maxValue = Math.max(...data.data);
        const barWidth = chartWidth / data.data.length - 10;
        
        // 绘制坐标轴
        ctx.strokeStyle = '#ccc';
        ctx.lineWidth = 1;
        
        // Y轴
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // X轴
        ctx.beginPath();
        ctx.moveTo(padding, ctx.canvas.height - padding);
        ctx.lineTo(ctx.canvas.width - padding, ctx.canvas.height - padding);
        ctx.stroke();
        
        // 绘制柱状图
        data.data.forEach((value, index) => {
            const x = padding + index * (chartWidth / data.data.length) + 5;
            const barHeight = (value / maxValue) * chartHeight;
            const y = ctx.canvas.height - padding - barHeight;
            
            // 绘制柱子
            ctx.fillStyle = color;
            ctx.fillRect(x, y, barWidth, barHeight);
            
            // 绘制数值
            ctx.fillStyle = '#333';
            ctx.font = '10px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(value, x + barWidth / 2, y - 5);
            
            // 绘制标签
            ctx.fillStyle = '#666';
            ctx.font = '10px Arial';
            ctx.textAlign = 'center';
            
            // 简化标签显示
            const label = data.labels[index];
            const shortLabel = label.length > 6 ? label.substring(0, 6) + '...' : label;
            ctx.fillText(shortLabel, x + barWidth / 2, ctx.canvas.height - padding + 15);
        });
    }
}

// 全局函数（用于HTML中的onclick调用）
function showSection(section) {
    messagesManager.showSection(section);
}

function filterMessages(status) {
    messagesManager.filterMessages(status);
}

function filterSubscriptions(status) {
    messagesManager.filterSubscriptions(status);
}

function toggleSelectAll(checkbox) {
    messagesManager.toggleSelectAll(checkbox);
}

function toggleBatchActions() {
    messagesManager.toggleBatchActions();
}

function batchDelete() {
    messagesManager.batchDelete();
}

function exportData() {
    messagesManager.exportData();
}

// 初始化系统
let messagesManager;

document.addEventListener('DOMContentLoaded', function() {
    messagesManager = new MessagesManager();
});